package com.longqin.business.service.impl;

import com.longqin.business.entity.BusRequirement;
import com.longqin.business.mapper.BusRequirementMapper;
import com.longqin.business.service.IBusRequirementService;
import com.longqin.business.util.OperationLog;
import com.longqin.business.util.RedisUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 需求管理 服务实现类
 * </p>
 *
 * @author longqin
 * @since 2024-12-23
 */
@Service
public class BusRequirementServiceImpl extends ServiceImpl<BusRequirementMapper, BusRequirement> implements IBusRequirementService {

	@Autowired
	BusRequirementMapper busRequirementMapper;
	
	@Autowired
	RedisUtil redisUtil;
	
	private static final String CODE_PREFIX = "XQSQ"; // 需求编码前缀
	private static final String CODE_REDIS_KEY = "requirement_code"; // 自增需求编码REDIS存储KEY
	
	@Override
    public BusRequirement getById(int id) {
		return  busRequirementMapper.selectById(id);
    }
	
	@Override
    public List<BusRequirement> getPage(String title, int organizationId, int startIndex, int pageSize) {
        return busRequirementMapper.selectPage(title, organizationId, startIndex, pageSize);
    }
    
	@Override
    public int getCount(String title, int organizationId) {
        return busRequirementMapper.selectCount(title, organizationId);
    }
	
	@OperationLog(title = "删除需求", content = "'需求id：' + #id", operationType = "1")
	@Override
    public int delete(int id) throws Exception {
		return busRequirementMapper.updateStatus(0, id);
    }
	
	@OperationLog(title = "创建需求", content = "'需求标题：' + #entity.getTitle()", operationType = "0")
	@Override
    public int create(BusRequirement entity) throws Exception {
		entity.setCode(generateCode(CODE_REDIS_KEY));
		return busRequirementMapper.insert(entity);
	}
	
	@OperationLog(title = "修改需求", content = "'需求名称：' + #entity.getTitle()", operationType = "2")
	@Override
    public int update(BusRequirement entity) throws Exception {
		return busRequirementMapper.updateById(entity);
	}
	
	// 生成需求编码
	private String generateCode(String key){
		String requestId = UUID.randomUUID().toString();
		int seq = 1;
		boolean isReleaseLock = true; // 是否释放锁
		String lockKey = key + "_lock";
		try {
			boolean mLock = redisUtil.lock(requestId, lockKey, 1 * 10);//锁的有效时间10秒
			if(mLock){
				isReleaseLock = false;
				seq = (int) redisUtil.incrKey(key, 1, getNowToNextDayMilliseconds(), TimeUnit.SECONDS);
				redisUtil.releaseLock(requestId, lockKey);//释放锁
				isReleaseLock = true;
			}
		} catch (Exception e) {

		}finally{
			if(!isReleaseLock){
				redisUtil.releaseLock(requestId, lockKey);
			}
		}
		LocalDate now = LocalDate.now();
		String code = CODE_PREFIX + now.format(DateTimeFormatter.ofPattern("yyyyMMdd")) + seq;
		return code;
	}
	
	// 今日剩余时间计算
    private Long getNowToNextDayMilliseconds() {
        //获取当前时间
        Calendar calendar = Calendar.getInstance();
        //当前天+1
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        //将时分秒毫秒都设为0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //减去当前时间获取插值
        return (calendar.getTimeInMillis() - System.currentTimeMillis());
    }
    
    @Override
    public BusRequirement getByWorkId(int workId) {
		return  busRequirementMapper.selectByWorkId(workId);
    }
}
